package com.minsf.springbootinit;

import cn.hutool.core.thread.ThreadUtil;
import org.openjdk.jol.info.ClassLayout;

/**
 * @Description
 * @Author minify
 * @Date 2024/1/21 19:00
 * @Project oj-backend
 */
public class UpdagradeHashCode {


    static Object objectLock = new Object();


    public static void m2() {
        Object o = new Object();
        synchronized (o) {
            System.out.println(o.hashCode()+"===xxx"+"=="+objectLock.hashCode());
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            Thread ix = new Thread(() -> {
                synchronized (objectLock) {
                    System.out.println(111);
                }
                synchronized (objectLock) {
                    System.out.println(222);
                }
                synchronized (objectLock) {
                    System.out.println(333);
                }
                synchronized (objectLock) {
                    System.out.println(111);
                    System.out.println(222);
                    System.out.println(333);
                }
            }, i+"");
            ix.start();
        }
    }

    private static void extracted() {
        // 触发偏向锁开启
        ThreadUtil.sleep(5000);
        Object lock = new Object();
        int i = lock.hashCode();
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
    }

    private static void changeZ() {
        // 触发偏向锁开启
        ThreadUtil.sleep(5000);
        Object lock = new Object();

        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
        // 偏向锁时获取hashcode，会撤销锁并直接升级为重锁
        int i = lock.hashCode();
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
    }
}
